import * as CONSTS from './index.const';
import { productsList } from '~/components/after-sale/products-list';
import { exchangeProductsList } from '~/components/after-sale/exchange-products-list';
import reason from '~/components/after-sale/reason/index.vue';
import addressFunc from '~/components/after-sale/address-func/index.vue';
import ElEditable from '@components/el-editable';
import { throttle, isObject } from 'lodash';
import {
  submitOrderChange,
  saveOrderChange,
  downloadFailUploadDataHH,
  downloadFailUploadDataTH,
  uploadReturnedExchangeProduct,
  uploadReturnedProduct,
  salesReturnDetails,
  getOrderType,
  wholeOrderReturn,
  queryOrderInfo,
  echoReturnProductList,
  echoExchangeProductList
} from '@api/m_mall_web_v1.js';
import { IndexService } from './index.service';
let indexService = new IndexService();

export default {
  name: 'purchaseExchangeOrder',
  inject: ['apiMMallWeb'],
  provide: {
    downloadFailUploadDataHH: downloadFailUploadDataHH,
    downloadFailUploadData: downloadFailUploadDataTH,
    uploadExchangeProduct: uploadReturnedExchangeProduct,
    uploadProduct: uploadReturnedProduct,
    exTemplateDownLoad: 'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/9ds2jnta6w6693lv5j57n5328twi2srl.xlsx',
    templateDownLoad: 'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/yjqoyms1x7cuwb1iv3s0rzwcj3cbu7fv.xlsx'
  },
  data() {
    return {
      ...CONSTS,
      active_index: 1,
      // 用于接口使用的绑定数据
      submit_data: {
        // 第一步
        supplier_id: '',
        contract_id: '',
        // 第二步产品
        return_goods: [],
        // 第二步原因
        return_reason: {
          reason_sel: '',
          reason_text: '',
          reason_imgs: [],
          reason_name: ''
        },
        // 第三步选择换货产品
        exchange_goods: [],
        // 第四步承运方式
        carryway_id: '',
        // 第四步地址
        full_address: {},
        orderCodeRelate: '',
        orderCode: '',
        orderDetailId: '',
        orderId: '',
        order_type_key: '',
        supplier_data: {},
        contract_data: {}
      },
      address_id: '',
      // 用于页面渲染使用的数据
      render_data: {
        order_type_rows: [],
        rows_carryway: []
      },
      // 用于各种状态的数据
      status: {
        isEdit: false,
        isFirstMount: true,
        dialogVisible: false,
        submit_loading: false
      },
      idKey: {
        orderCode: '',
        orderCodeRelate: '',
        orderDetailId: '',
        orderId: ''
      }
    };
  },
  components: {
    ElEditable,
    productsList,
    exchangeProductsList,
    reason,
    addressFunc
  },
  async created() {
    let result_carryway = await this.apiMMallWeb.CommonEnumOrderV1ApiPOST({
      query: {
        indexCode: 'transportType'
      }
    });
    this.render_data.rows_carryway = result_carryway;
    // 编辑模式
    // 这个地方的编辑反显逻辑，跟after-sale/exchange-order中的反显逻辑是一样的
    this.getOrderDetailInfo();
  },
  mounted() {
    // 初始化导航栏按钮
    this.initGlobalBtn();
  },
  computed: {
    queryParams() {
      return {
        orderType: this.$route.query.orderType, //1是新建，2是编辑
        orderId: this.$route.query.orderId
      };
    }
  },
  methods: {
    getOrderDetailInfo() {
      this.$axios({
        method: 'post',
        url: queryOrderInfo,
        data: {
          orderId: this.queryParams.orderId
        }
      }).then(res => {
        let result = res.data.payload;
        console.log(result, 'result');
        this.busModel = result.busModel;
        this.getOrderTypeRows(result);
        // 这里和新建有些不同的地方就是，这里不用通过id反向匹配经销商和合同，所以，直接赋值就好了
        this.submit_data.supplier_data = result.supplierVo;
        this.submit_data.contract_data = result.contractVo;
        // 如果能取到退货单id，说明是编辑，这里暂时先这样
        console.log(typeof this.queryParams.orderType, 'this.queryParams.orderType')
        if (String(this.queryParams.orderType) === '2') {
          // 设置地址
          this.address_id = result.addressResDto.userAddressId;
          this.submit_data.full_address = result.addressResDto;
          // 承运方式
          this.submit_data.carryway_id = String(result.transportType || '');
          // 其他id，用于接口提交、暂存使用
          // 编辑的时候orderCode要取换货单的orderCode，因为编辑的时候本单就已经是换货单了，所以取到的就是orderCode
          this.idKey.orderCode = result.orderCode;
          this.idKey.orderId = result.orderId;
          this.idKey.orderDetailId = result.orderDetailId;
          // 这个地方要注意一下啊，创建原单退换货的时候，分为原单号和退换货单号。
          // 但是字段都是orderCode，需要前端从接口中获取，不同接口入参的key还是不一样的。
          this.idKey.orderCodeRelate = result.orderCodeRelate;
          // 给submit中的对应字段赋值，是为了可以传递给自组件使用。
          this.submit_data.orderCodeRelate = result.orderCodeRelate;
          this.status.isEdit = true;
          this.getDetailData(result);
          this.getEchoReturnProductList(result);
        } else {
          // 新建的话，orderCodeRelate就是orderCode
          this.idKey.orderCodeRelate = result.orderCode;
          // 给submit中的对应字段赋值，是为了可以传递给自组件使用。
          this.submit_data.orderCodeRelate = result.orderCode;
        }
      })
    },
    getDetailData(params) {
      console.log(params)
      this.$axios({
        url: salesReturnDetails,
        method: 'post',
        data: {
          orderId: params.orderIdReturn
        }
      }).then(res => {
        let result = res.data.payload ? res.data.payload : {};
        this.render_data.orderData = result.orderData;
        // 设置退货原因
        this.submit_data.return_reason.reason_sel = result.orderData.returnReasonCode;
        this.submit_data.return_reason.reason_text = result.orderData.returnReasonDetail;
        this.submit_data.return_reason.reason_name = result.orderData.returnReasonName
        this.submit_data.return_reason.reason_imgs = result.commonFile.map(item => item.fileUrl);
        // if (this.queryParams.orderType === '2') {
        //   // 给submit中的对应字段赋值，是为了可以传递给自组件使用。
        //   this.submit_data.orderCodeRelate = result.orderData.orderCodeExchange;
        // }
      });
    },
    handlerMiddleEvent(resolve = () => { }, reject = () => { }) {
      this.$confirm('若修改退货产品，添加的新换产品将会清空', '确认修改退货产品么？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(resolve)
        .catch(reject);
    },
    makeSureToAddWhole() {
      if (!!this.submit_data.exchange_goods.length) {
        this.handlerMiddleEvent(
          () => {
            this.addWholeOrderProducts()
            this.submit_data.exchange_goods = []
          }
        );
      } else {
        this.addWholeOrderProducts()
      }
    },
    addWholeOrderProducts() {
      this.$axios({
        method: 'post',
        url: wholeOrderReturn,
        data: {
          orderCode: this.idKey.orderCodeRelate
        }
      }).then(res => {
        let result = res.data.payload;
        if (result.isPartialReturns === '1') {
          this.$message({ type: 'warning', message: '存在部分退换货，只展示剩余可退换产品' });
        }
        if (result.returnProductList.content && result.returnProductList.content.length > 0) {
          this.submit_data.return_goods = result.returnProductList.content.map(it => {
            return {
              ...it,
              productCount: Number(it.returnCount) || 1,
              staticProductCount: Number(it.returnCount) || 1,// 这个字段，是用于products-list组件中，更换数量时拦截回归数据使用
              returnCount: Number(it.returnCount),
              mixsIds: it.orginalOrderCode + it.seqNo + it.productCode + it.batchNo + it.validDate + it.referencePrice,
            }
          });
        } else {
          this.$message({ type: 'warning', message: '没有可以整单退货的产品' })
        }
      })
    },
    getEchoExchangeProductList(result, returnGoods) {
      this.$axios({
        method: 'post',
        url: echoExchangeProductList,
        data: {
          orderCode: result.orderCode,
          returnProductList: returnGoods.map(it => {
            return {
              productName: it.productName,
              returnQuantity: it.returnQuantity,
            }
          })
        }
      }).then(res => {
        let data = res.data.payload?.content;
        this.submit_data.exchange_goods = data.map(it => {
          return {
            ...it,
            attribute1: it.model || it.specs,
            productUnitName: it.productUnit,
            productCount: Number(it.exchangeQuantity),
            exhcangeCount: Number(it.exchangeableQuantity),
            referencePrice: it.productPrice,
            mixsIds: it.productCode,
          }
        })
        this.setInitialProductsDataNums()
      });
    },
    setInitialProductsDataNums() {
      let exProductNamesNum = this.$refs.exchangeProductsList.concatCommonNameProduct(this.submit_data.exchange_goods, 'productCount');
      let returnGoodsCurNums = this.$refs.exchangeProductsList.concatCommonNameProduct(this.submit_data.return_goods, 'productCount');
      // 初始化可选数量
      returnGoodsCurNums.forEach(rGood => {
        this.submit_data.exchange_goods.forEach(item => {
          if (item.productName === rGood.name) {
            this.$set(item, 'optionalQuantity', rGood.commonNameTotalNum);
          }
        });
      });
      // 初始化已选数量
      this.submit_data.exchange_goods.forEach(item => {
        this.$set(item, 'selectedQuantity', 0);
        exProductNamesNum.forEach(exGood => {
          if (item.productName === exGood.name) {
            this.$set(item, 'selectedQuantity', exGood.commonNameTotalNum);
          }
        });
      });
      console.log(this.submit_data.exchange_goods, 'this.submit_data.exchange_goods')
    },
    getEchoReturnProductList(result) {
      this.$axios({
        method: 'post',
        url: echoReturnProductList,
        data: {
          orderCode: result.orderCodeReturn
        }
      }).then(res => {
        let data = res.data.payload?.content;
        this.submit_data.return_goods = data.map(it => {
          return {
            ...it,
            attribute1: it.model || it.specs,
            productUnitName: it.productUnit,
            productCount: Number(it.returnQuantity) || 1,
            staticProductCount: Number(it.returnQuantity) || 1,// 这个字段，是用于products-list组件中，更换数量时拦截回归数据使用
            returnCount: Number(it.returnableQuantity),
            referencePrice: it.productPrice,
            mixsIds: it.orginalOrderCode + it.seqNo + it.productCode + it.batchNo + it.validDate + it.referrencePrice,
          }
        });
        this.isReturnProductsOccupy(this.submit_data.return_goods);
        this.getEchoExchangeProductList(result, this.submit_data.return_goods)
      });
    },
    // 判断退货产品是否被其他订单占用
    isReturnProductsOccupy(products) {
      let flag = products.some(item => Number(item.returnableQuantity) < Number(item.returnQuantity));
      if (flag) {
        this.$alert('暂存的退换货产品被别的订单使用，请重新添加换货产品', '', {
          confirmButtonText: '知道了',
          callback: action => {
            this.submit_data.return_goods = this.submit_data.return_goods.filter(item => (Number(item.returnableQuantity) > 0));
            this.submit_data.exchange_goods = [];
          }
        });
      }
    },
    getOrderTypeRows(result) {
      this.$axios({
        method: 'post',
        url: getOrderType,
        data: {
          busModel: result.busModel,
          supplierCode: '000'
        }
      }).then(res => {
        let result = res.data.payload || {};
        this.render_data.order_type_rows = result;
        this.submit_data.order_type_key = this.render_data.order_type_rows.find(item => {
          return item.orderTypeName.includes('换货');
        }).ddbm;
      });
    },
    getBackExchangeGoods(goods) {
      this.submit_data.exchange_goods = goods;
    },
    getSeledAddress(val) {
      this.submit_data.full_address = val;
    },
    // 全局性初始化配置
    // 导航栏按钮
    // 上一步
    onPrev() {
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    // 下一步
    onNext() {
      console.log(this.submit_data);
      let verify_result = indexService.verifyStep(this.active_index, this.submit_data);
      if (verify_result.pass === true) {
        if (this.active_index++ >= 3) this.active_index = 3;
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verify_result.message
        });
      }
      this.initGlobalBtn();
    },
    // 暂存
    onSaveDraft() {
      console.log(this.submit_data, 'submit_data');
      let verify_result = indexService.verifyStep(this.active_index, this.submit_data);
      if (verify_result.pass === true) {
        this.saveProgress();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verify_result.message
        });
      }
    },
    saveProgress: throttle(
      function () {
        console.log(this.splitSubmitDataBySteps(), '--------------------');
        // this.saveTheData();
        this.$axios({
          url: saveOrderChange,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            let result = isObject(res.data.payload) ? res.data.payload : {};
            // 新建，并暂存后，本来的以下字段已经有了，需要赋值
            this.idKey.orderCode = result.orderCode;
            this.idKey.orderId = result.orderId;
            this.idKey.orderDetailId = result.orderDetailId;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(err => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    getReasonName(reasonName) {
      this.submit_data.return_reason.reason_name = reasonName;
    },
    reStructSubmitData() {
      return {
        busModel: '1',
        returnReasonCode: this.submit_data.return_reason.reason_sel,
        returnReason: this.submit_data.return_reason.reason_name,
        returnReasonDetail: this.submit_data.return_reason.reason_text,
        supplierVo: this.submit_data.supplier_data, // 供应商
        contractVo: this.submit_data.contract_data, // 合同
        saveProductVO: this.submit_data.return_goods, // 采购产品
        saveProductVOChange: this.submit_data.exchange_goods,
        addressResDto: this.submit_data.full_address, // 地址
        commonFileForms: this.submit_data.return_reason.reason_imgs.map(item => {
          let name = item.substring(item.lastIndexOf('/') + 1);
          return {
            fileName: name.split('.')[0],
            fileType: name.split('.')[1],
            fileUrl: item
          };
        }), // 原因图片
        transportType: this.submit_data.carryway_id,
        orderCode: this.idKey.orderCode, // 订单编码
        orderCodeRelate: this.idKey.orderCodeRelate,
        orderDetailId: this.idKey.orderDetailId, // 订单详情id
        orderId: this.idKey.orderId, // 订单id
        orderTypeId: this.render_data.order_type_rows.find(item => {
          return item.ddbm === this.submit_data.order_type_key;
        }).orderTypeId,
        orderType: this.submit_data.order_type_key,
        createType: 2 // 1独立创建，2原单创建
      };
    },
    onSubmit: throttle(
      function () {
        this.status.submit_loading = true;
        this.$axios({
          url: submitOrderChange,
          method: 'post',
          data: this.reStructSubmitData()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$router.push('/purchase-order/wholesale/list');
              this.$message({
                message: '订单提交成功',
                type: 'success'
              });
            }
          })
          .catch(err => {
            if(err.data.code === '200001') {
              this.$router.push('/purchase-order/wholesale/list');
            }
          })
          .finally(() => {
            this.status.dialogVisible = false;
            this.status.submit_loading = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    isSubmitProductsMatchRules(returnGoods, exchangeGoods) {
      // 需要把双方的同名的整合到一起再做对比
      let rGoods = this.$refs.exchangeProductsList.concatCommonNameProduct(returnGoods, 'productCount');
      let exGoods = this.$refs.exchangeProductsList.concatCommonNameProduct(exchangeGoods, 'productCount');
      let hahaArr = [];
      rGoods.forEach(r => {
        let obj = {
          name: '',
          rNum: 0,
          eNum: 0
        };
        obj.name = r.name;
        obj.rNum = r.commonNameTotalNum;
        exGoods.forEach(curGoods => {
          if (r.name === curGoods.name) {
            obj.eNum = curGoods.commonNameTotalNum;
          }
        });
        hahaArr.push(obj);
      });
      console.log(hahaArr, 'hahaArr')
      let flag = hahaArr.some(item => {
        return item.eNum !== item.rNum;
      });
      console.log(flag)
      return flag
    },
    // 打开确认提交弹窗
    showConfirmDialog() {
      let verify_result = indexService.verifyStep(3, this.submit_data);
      if (verify_result.pass === true) {
        // 做一下退货产品和换货产品匹配的校验
        if (this.isSubmitProductsMatchRules(this.submit_data.return_goods, this.submit_data.exchange_goods)) {
          this.$message({
            type: 'error',
            message: '换货数量不正确'
          })
          return;
        }
        this.status.dialogVisible = true;
        // this.saveTheData();
      } else {
        this.$notify({
          title: '必填项',
          message: verify_result.message,
          type: 'warning'
        });
      }
    },
    initGlobalBtn() {
      let btnObj = {
        type: 'btn',
        arr: []
      };
      let saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      let prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      let nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      let submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      if (this.active_index !== 1) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 3) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      btnObj.arr.push(saveDraftBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    splitSubmitDataBySteps() {
      let cur_step = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      let split_submit_data = {
        busModel: '1',
        // financialEntry: '',
        // receiptInvoice: '',
        returnReason: '',
        returnReasonCode: '',
        returnReasonDetail: '',
        transportType: '', // 承运方式
        supplierVo: {}, // 供应商
        contractVo: {}, // 合同
        saveProductVO: [], // 采购产品
        saveProductVOChange: [], // 换货商品
        addressResDto: {}, // 地址
        commonFileForms: [], // 原因图片
        orderCode: this.idKey.orderCode, // 订单编码
        orderDetailId: this.idKey.orderDetailId, // 订单详情id
        orderId: this.idKey.orderId, // 订单id
        orderCodeRelate: this.idKey.orderCodeRelate,
        orderType: this.submit_data.order_type_key,
        orderTypeId: this.render_data.order_type_rows.find(item => {
          return item.ddbm === this.submit_data.order_type_key;
        }).orderTypeId,
        createType: 2 // 1独立创建，2原单创建
      };
      // 第一步
      switch (cur_step) {
        case 1:
          split_submit_data.supplierVo = this.submit_data.supplier_data;
          split_submit_data.contractVo = this.submit_data.contract_data;
          split_submit_data.saveProductVO = this.submit_data.return_goods;
          split_submit_data.returnReasonCode = this.submit_data.return_reason.reason_sel;
          split_submit_data.returnReason = this.submit_data.return_reason.reason_name;
          split_submit_data.returnReasonDetail = this.submit_data.return_reason.reason_text;
          split_submit_data.commonFileForms = this.submit_data.return_reason.reason_imgs.map(item => {
            let name = item.substring(item.lastIndexOf('/') + 1);
            return {
              fileName: name.split('.')[0],
              fileType: name.split('.')[1],
              fileUrl: item
            };
          });
          break;
        case 2:
          split_submit_data.supplierVo = this.submit_data.supplier_data;
          split_submit_data.contractVo = this.submit_data.contract_data;
          split_submit_data.saveProductVO = this.submit_data.return_goods;
          split_submit_data.returnReasonCode = this.submit_data.return_reason.reason_sel;
          split_submit_data.returnReason = this.submit_data.return_reason.reason_name;
          split_submit_data.returnReasonDetail = this.submit_data.return_reason.reason_text;
          split_submit_data.commonFileForms = this.submit_data.return_reason.reason_imgs.map(item => {
            let name = item.substring(item.lastIndexOf('/') + 1);
            return {
              fileName: name.split('.')[0],
              fileType: name.split('.')[1],
              fileUrl: item
            };
          });
          split_submit_data.saveProductVOChange = this.submit_data.exchange_goods;
          break;
        // 第四步就比较简单了
        case 3:
          split_submit_data.supplierVo = this.submit_data.supplier_data;
          split_submit_data.contractVo = this.submit_data.contract_data;
          split_submit_data.saveProductVO = this.submit_data.return_goods;
          split_submit_data.returnReasonCode = this.submit_data.return_reason.reason_sel;
          split_submit_data.returnReason = this.submit_data.return_reason.reason_name;
          split_submit_data.returnReasonDetail = this.submit_data.return_reason.reason_text;
          split_submit_data.addressResDto = this.submit_data.full_address;

          split_submit_data.commonFileForms = this.submit_data.return_reason.reason_imgs.map(item => {
            let name = item.substring(item.lastIndexOf('/') + 1);
            return {
              fileName: name.split('.')[0],
              fileType: name.split('.')[1],
              fileUrl: item
            };
          });
          split_submit_data.saveProductVOChange = this.submit_data.exchange_goods;
          split_submit_data.transportType = this.submit_data.carryway_id;
          break;
      }
      return split_submit_data;
    },
    clearExchangeGoods() {
      this.submit_data.exchange_goods = [];
    }
  }
};
